package com.dgut.declaration_of_health.config;

//import com.dgut.security.VerifyException;
//import com.dgut.security.filter.RestAuthenticationFilter;
//import com.dgut.security.service.CustomUserDetailsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.cors.CorsUtils;

import java.util.HashMap;

@Configuration
@EnableWebSecurity(debug = true) //启动 SpringSecurity 过滤器链功能
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 认证管理器：
     * 1、认证信息提供⽅式（⽤户名、密码、当前⽤户的资源权限）
     * 2、可采⽤内存存储⽅式，也可能采⽤数据库⽅式等
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    }

    @Bean
    BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;
    }

    /**
     * 资源权限配置（过滤器链）:
     * 1、被拦截的资源
     * 2、资源所对应的⻆⾊权限
     * 3、定义认证⽅式：httpBasic 、httpForm
     * 4、定制登录⻚⾯、登录请求地址、错误处理⽅式
     * 5、⾃定义 spring security 过滤器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.addFilterAt(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).csrf().disable();

        http.authorizeRequests()
                //处理跨域请求中的Preflight请求
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers(HttpMethod.GET, "/user/**").permitAll()
                .antMatchers(HttpMethod.GET, "/kaptcha/**").permitAll()
                .anyRequest().authenticated().and().cors();
    }
}
